<template>
  <div>
    <article class="main-breadcrumb">
      <el-breadcrumb separator=">" class="main-breadcrumb-wrap">
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home">排程管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home" @click="getTo">模板管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home">模板详情</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </article>
    <div class="nx-content">
      <div class="flex-bet">
        <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
          <div style="margin-left: 5rem">
            <el-form-item label="">
              <el-select @change="getFishArrary" v-model="searchForm.boxCode" placeholder="请选择控制箱名称" style="width: 200px !important" clearable>
                <el-option v-for="item in objBoxArrary" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select v-model="searchForm.fishpondCode" placeholder="请选择鱼池编号" style="width: 200px !important" clearable>
                <el-option v-for="item in fishArrary" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <div v-allow="'030102'" class="search-btn" @click="onSubmit"></div>
            </el-form-item>
            <el-form-item>
              <div v-allow="'030102'" class="reset-btn" @click="resetForm"></div>
            </el-form-item>
          </div>
          <div style="display: flex;margin-bottom: 1rem;margin-left: 4rem;">
            <div style="display: flex">
              <Import @onSubmit="onSubmit" V-allow="050101" :data="dataObj" :url="'configFishpondTask/schedulingImportExcel'"></Import>
              <el-button style="
                        background-color: #0a5fb2;
                        border-color: #0a5fb2;
                        border-radius: 60px;
                        width: 10rem;
                        height: 3rem;
                      " v-allow="'050101'" @click="exportFile" icon="el-icon-download" type="success">日常导出</el-button>
              <el-button style="
                        background-color: #0a5fb2;
                        border-color: #0a5fb2;
                        border-radius: 60px;
                        width: 10rem;
                        height: 3rem;
                      " v-allow="'050101'" @click="submitRW" icon="el-icon-notebook-2" type="success">日常任务下发</el-button>
            </div>
            <!-- 投料的导入导出 -->
            <div style="display: flex">
              <Import_c @onSubmit="onSubmit" V-allow="050101" :data="dataObj" :url="'configFishpondTask/schedulingImportExcel'"></Import_c>
              <el-button style="
                        background-color: #0a5fb2;
                        border-color: #0a5fb2;
                        border-radius: 60px;
                        width: 10rem;
                        height: 3rem;
                      " v-allow="'050101'" @click="exportFile_tl" icon="el-icon-download" type="success">投料导出</el-button>
              <el-button style="
                        background-color: #0a5fb2;
                        border-color: #0a5fb2;
                        border-radius: 60px;
                        width: 10rem;
                        height: 3rem;
                      " v-allow="'050101'" @click="submitRW_tl" icon="el-icon-notebook-2" type="success">投料任务下发</el-button>
            </div>
          </div>

        </el-form>
        <div class="left-title flex">
          <div v-allow="'030101'" style="margin-top: 1rem" class="add-btn" @click="handleAdd()">
            添加排程
          </div>
        </div>
      </div>
      <NxTable :table-cols="tableCols" :table-data="newList" :pag-ination="pagination" :isIndex="false" class="table-wrap" @refresh="refresh">
        <template slot="type" slot-scope="scope">
          <span v-if="scope.row.type == 0">投料</span>
          <span v-if="scope.row.type == 1">换水</span>
          <span v-if="scope.row.type == 2">排污</span>
          <span v-if="scope.row.type == 3">增氧</span>
        </template>

        <template slot="dischargeWaterGroupId" slot-scope="scope">
          <span>{{ scope.row.dischargeWaterGroupId }}组</span>
        </template>
        <template slot="operation" slot-scope="scope">
          <span v-allow="'030103'" @click="handleEdit(scope.row)" class="nx-btn nx-edit">编辑</span>
          <span v-allow="'030104'" @click="handleDelete(scope.row)" class="nx-btn nx-del">删除</span>
        </template>
      </NxTable>
    </div>
    <AddEditDialog :ruler="ruler" :Aid="Aid" :baseId="baseId" :companyId="companyId" :addEditId="addEditId" :addEditStatus="addEditStatus" :addEditIsDialog="addEditIsDialog">
    </AddEditDialog>
    <el-dialog title="导入数据" :visible.sync="dialogVisible" width="500px" :before-close="handleClose">
      <div class="equipmentcenter-opption-box">
        <el-form ref="ruleForm" label-position="left" :model="form" label-width="0px">
          <!-- :action="$serverUrl + 'model/ruleDevice/importModelRuleDevice'"
              :data="{ token: form.token }"
              name="fileName"
              :before-upload="handleChange"
              :on-success="handleAvatarSuccess" -->
          <!-- :file-list="fileList" -->

          <!-- <el-form-item label="" prop="image" style="width: 100%">
            <el-upload
              class="upload-demo"
              action="#"
              :show-file-list="false"
              :on-change="handleExcel"
              accept="'.xlsx','.xls'"
              :auto-upload="false"
              :headers="headers"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传excel(.xls和.xlsx)文件
              </div>
            </el-upload>
          </el-form-item> -->
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import NxTable from '@/components/NxTable.vue'
import AddEditDialog from './components/addEditDialog.vue'
import Import from '@/components/Import.vue'
import Import_c from '@/components/Import_c.vue'
import { Page } from '@/utils/pagination'
import { delConfigFishpondTasksByChart, getSysCompanyBases, getObjBoxTaskList, taskExportExcel, taskImportExcel, sendBaseBoxCmd, saveDataHisSendtoFeedTask, feedingExportExcel, getObjBoxs, getFishpondsByBoxId } from '@/api/system'
import { getCompanyInfoTree } from '@/api/company'
import { getObjFishponds } from '@/api/fishpond'

export default {
  components: {
    NxTable,
    AddEditDialog,
    Import,
    Import_c
  },
  // 表格数据
  data() {
    return {
      dataObj: {},
      // headers: { 'Content-Type': 'multipart/form-data;charset=UTF-8' },
      form: {
        token: ''
      },
      ruler: [],
      // 查询字段
      baseId: '',
      companyId: '',
      fileList: [],
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        baseId: '',
        code: '',
        userType: '',
        companyId: Number(window.localStorage.getItem('companyId')),
        deviceStatus: '',
        name: '',
        tailWaterModel: '',
        type: ''
      },
      // 表格字段
      tableCols: [
        {
          label: '开始时间',
          prop: 'startTime',
          align: 'center'
        },

        {
          label: '结束时间',
          prop: 'endTime',
          align: 'center'
        },
        {
          label: '类型',
          slot: 'type',
          align: 'center'
        },
        {
          label: '一舱每日投喂量(千克)',
          prop: 'feedingAmount',
          align: 'center',
          width: 170
        },
        {
          label: '一舱总投喂量(千克)',
          prop: 'feedingTotal',
          align: 'center',
          width: 170
        },
        {
          label: '二舱每日投喂量(千克)',
          prop: 'feedingAmountSecond',
          align: 'center',
          width: 170
        },
        {
          label: '二舱总投喂量(千克)',
          prop: 'feedingTotalSecond',
          align: 'center',
          width: 170
        },
        {
          label: '控制箱编号',
          prop: 'boxName',
          align: 'center'
        },
        {
          label: '排水分组',
          slot: 'dischargeWaterGroupId',
          align: 'center'
        },
        {
          label: '鱼池编号',
          prop: 'fishpondCode',
          align: 'center'
        }
        // {
        //   label: '操作',
        //   slot: 'operation',
        //   align: 'center',
        //   width: 180,
        //   fixed: 'right',
        // },
      ],
      tableData: [],
      pagination: new Page(),
      crumbsStatus: '', // 三级面包屑名称
      typeDialog: false,
      addEditIsDialog: false, // 添加编辑页面状态
      addEditStatus: 'add',
      addEditId: '', // 添加编辑rowid
      baseArray: [], // 角色集合
      companyArray: [], // 公司集合
      userType: '', // 用户类型（0超级管理员，1公司管理员，2公司员工）
      newList: [],
      Aid: '',
      dialogVisible: false,
      objBoxArrary: [],
      fishArrary: []
    }
  },
  // 初始化加载

  mounted() {
    this.userType = Number(window.localStorage.getItem('userType'))
    this.searchForm.userType = this.userType
    this.baseId = this.$route.query.baseId
    this.boxId = this.$route.query.id
    this.companyId = this.$route.query.companyId
    this.getCompanyInfoTree()
    this.getFirstList()
    // this.getdrainageList()
    this.dataObj.modelId = this.boxId
    this.getObjBoxs()
    // this.getObjFishponds()
  },

  // 自定义方法
  methods: {
    // 获取控制箱下的鱼池
    getFishArrary(val) {
      getFishpondsByBoxId({ id: val }).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: res.msg
          })
          this.fishArrary = res.data
        }
      })
    },
    submitRW() {
      // if (!this.searchForm.baseId) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请选择基地',
      //   })
      //   return false
      // }
      sendBaseBoxCmd({ id: this.baseId }).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: res.msg
          })
          this.drainageList = res.data
        }
      })
    },
    submitRW_tl() {
      // if (!this.searchForm.baseId) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请选择基地',
      //   })
      //   return false
      // }
      saveDataHisSendtoFeedTask({ id: this.baseId }).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: res.msg
          })
          this.drainageList = res.data
        }
      })
    },
    // 导出模板
    exportFile() {
      taskExportExcel({ id: this.boxId }).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '导出成功'
          })
          const url = res.msg
          window.open(url) //通过这个打开网页就可下载导出
        } else {
          this.$message({
            type: 'warning',
            message: res.msg
          })
        }
      })
    },
    exportFile_tl() {
      feedingExportExcel({ id: this.boxId }).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '导出成功'
          })
          console.log(res.msg)
          const url = res.msg
          window.open(url) //通过这个打开网页就可下载导出
        } else {
          this.$message({
            type: 'warning',
            message: res.msg
          })
        }
      })
    },
    // 导入数据
    uploadFile() {
      this.dialogVisible = true
    },
    // 关闭导入弹窗
    handleClose() {
      this.dialogVisible = false
    },
    // 上传成功
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: res.msg
        })
        this.listStorageCycle()
      } else {
        this.$message.error(res.msg)
      }
    },
    // 上传Excel
    // handleChange(file) {
    //   var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
    //   const extension = testmsg === 'xls'
    //   const extension2 = testmsg === 'xlsx'
    //   if (!extension && !extension2) {
    //     this.$message({
    //       message: '上传文件只能是 xls、xlsx格式!',
    //       type: 'warning',
    //     })
    //   }
    //   return extension || extension2
    // },

    // getdrainageList() {
    //     let id = {
    //         id: this.baseId
    //     }

    //     getDischargeWaterGroupIds(id).then((res) => {
    //         if (res.code == 200) {
    //             this.drainageList = res.data;
    //         }
    //     });
    // },
    getTo() {
      this.$router.push({
        path: `/schedule/template`
      })
    },
    handleDetail(row) {
      // <span v-if="scope.row.type == 0">进水控制箱</span>
      //     <span v-if="scope.row.type == 1">鱼池控制箱</span>
      //     <span v-if="scope.row.type == 2">尾水控制箱</span>
      // let type = ''
      // if (row.type == 0) {
      //   type = '进水控制箱'
      // } if (row.type == 1) {
      //   type = '鱼池控制箱'
      // } if (row.type == 2) {
      //   type = '尾水控制箱'
      // }
      this.$router.push({
        path: `/schedule/scheduledetails`
      })
    },
    // 查询
    onSubmit() {
      this.pagination.pageNum = 1
      this.getFirstList()
    },
    // 分页查询
    refresh(val) {
      this.searchForm.pageNum = val.pageNum
      this.searchForm.pageSize = val.pageSize
      this.getFirstList()
    },
    // 重置
    resetForm() {
      this.searchForm = {
        pageNum: 1,
        pageSize: 10,
        baseId: '',
        code: '',
        companyId: '',
        fishpondCode: '',
        boxCode: ''
      }

      this.getFirstList()
    },
    getFirstList() {
      let a = {
        modelId: this.boxId,
        baseId: this.baseId,
        boxCode: this.searchForm.boxCode,
        fishpondCode: this.searchForm.fishpondCode
      }

      getObjBoxTaskList(a).then((res) => {
        if (res.code == 200) {
          this.newList = []
          this.tableData = res.data
          this.pagination.count = res.data.total
          this.tableData.forEach((item) => {
            if (item.taskList) {
              item.taskList.forEach((i) => {
                i.boxName = item.boxName
                i.fishpondCode = item.fishpondCode
                this.newList.push(i)
              })
            }
          })
          console.log(this.newList)
        }
      })
    },
    // 查询列表
    getList() {
      this.searchForm.baseId = this.baseId
      getObjBoxTaskList(this.searchForm).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.data
          this.pagination.count = res.data.total
          this.tableData.forEach((item) => {
            if (item.taskList) {
              item.taskList.forEach((i) => {
                i.boxName = item.boxName
                i.fishpondCode = item.fishpondCode
                this.newList.push(i)
              })
            }
          })
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delConfigFishpondTasksByChart({ id: row.id }).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: res.msg
              })
              this.getFirstList()
            }
          })
        })
        .catch((err) => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 添加
    handleAdd() {
      this.Aid = ''
      this.addEditId = this.boxId
      this.addEditStatus = 'add'
      this.addEditIsDialog = true
    },
    // 编辑
    handleEdit(row) {
      this.Aid = row.id + ''
      this.addEditId = this.boxId
      this.addEditStatus = 'edit'
      this.addEditIsDialog = true
    },
    // 编辑添加取消关闭
    closeAddEdit() {
      this.addEditIsDialog = false
    },
    // 面包屑
    crumbsClick() {
      this.typeDialog = false
    },
    // 获取全部控制箱
    getObjBoxs() {
      getObjBoxs({ id: this.baseId }).then((res) => {
        if (res.code == 200) {
          this.objBoxArrary = res.data
        }
      })
    },
    // 获取全部鱼池
    // getObjFishponds() {
    //   getObjFishponds({ baseId: this.baseId, companyId: this.companyId }).then(
    //     (res) => {
    //       if (res.code == 200) {
    //         this.fishArrary = res.data
    //       }
    //     }
    //   )
    // },
    // 启用、禁用
    handleStatus(row) {
      openOrCloseSysUser({ id: row.id }).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: res.msg
          })
          this.getList()
        }
      })
    },
    // 用户类型切换
    typeChange() {
      this.searchForm.companyId = ''
      this.companyArray = []

      this.searchForm.roleId = ''
      this.baseArray = []

      // 获取公司列表
      this.getCompanyInfoTree()

      // 查询
      this.onSubmit()
    },
    // 获取公司列表
    getCompanyInfoTree() {
      if (this.searchForm.userType == 0) {
        // 超级管理员，公司只有一个总公司
        getCompanyInfoTree().then((res) => {
          if (res.code == 200) {
            this.companyArray = res.data
          }
        })
      } else {
        getCompanyInfoTree({ id: 0 }).then((res) => {
          if (res.code == 200) {
            this.companyArray = res.data
          }
        })
      }
    },
    // 公司下拉切换
    changeTreeItem(val) {
      if (val) {
        this.searchForm.companyId = val[val.length - 1]
      } else {
        this.searchForm.companyId = ''
      }

      this.searchForm.baseId = ''
      this.baseArray = []

      this.getList()

      // 获取角色列表
      this.getSysCompanyBases()
    },
    // 获取角色列表
    getSysCompanyBases() {
      if (this.searchForm.companyId === '' || this.searchForm.companyId == null) {
        return
      }

      getSysCompanyBases({ id: this.searchForm.companyId }).then((res) => {
        if (res.code == 200) {
          this.baseArray = res.data
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.main-breadcrumb {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 76px;
  border-bottom: solid 20px #f2f2f2;
  padding-left: 20px;

  .main-breadcrumb-wrap {
    font-size: 16px;
    line-height: 68px;

    .main-breadcrumb-home {
      cursor: pointer;
      color: #666666;
      font-weight: bold;
    }

    .main-breadcrumb-sp {
      color: #666666;
      font-weight: bold;
    }
  }
}
</style>
